package org.genuflex.components
{
	import mx.controls.Tree;
	import mx.collections.ArrayCollection;
	import org.genuflex.utils.GenuflexDataFunctions;
	
	public class GenuflexTree extends Tree
	{
		public function GenuflexTree() {
			addEventListener("render", onRender);
		}
		
		protected var previousOpenItems : ArrayCollection;
		protected var refreshTree : Boolean = false;
		
		private function stashOpenItems() : void {
			//Stash the open items
			if ((this.openItems as Array).length > 0) {
				previousOpenItems = new ArrayCollection(this.openItems as Array);				
			}
		}

		public override function set dataProvider(object : Object) : void {
			//Grab the currently open items
			stashOpenItems();
			refreshTree = !GenuflexDataFunctions.isEmpty(object);
			
			super.dataProvider = object;
		}	
		
		private function onRender(event : * = null):void{
			if(refreshTree){
				invalidateList();
				refreshTree = false;
				
				//The objects in the tree now may be equal in a logical sense,
				// but aren't the same instances.  So, we'll use GenuflexDataFunctions.areSame
				// to find the matching objects
				if (previousOpenItems != null) {
					var newOpenItems : ArrayCollection = new ArrayCollection();					
					
					if (dataProvider != null) {
						for each(var newObj : Object in dataProvider) {
							for each(var prevObj : Object in previousOpenItems) {
								if (GenuflexDataFunctions.areSame(newObj, prevObj)) {
									newOpenItems.addItem(newObj);
								}
							}
							
						}
					}
					
					openItems = Object(newOpenItems.toArray());
				}
				
				validateNow();				
			}
		}
		
	}
}